package redis

import (
	"common/helper"
	"context"
	"github.com/go-redis/redis/v8"
	"time"
)

type RedisLock struct {
	key   string
	value string
	ttl   time.Duration
}

func NewRedisLock(key string, value string, ttl time.Duration) *RedisLock {
	return &RedisLock{
		key:   key,
		value: value,
		ttl:   ttl,
	}
}

// Lock 尝试获取锁，并在锁被占用时等待直到获取到锁或超时
func Lock(redis *redis.Client, key string) bool {

	lock := NewRedisLock(key, "uniqueValue", 3*time.Second)

	endTime := time.Now().Add(4 * time.Second)
	for {
		// 尝试获取锁
		result, err := redis.SetNX(context.Background(), lock.key, lock.value, lock.ttl).Result()
		if err != nil {
			helper.InfoLog("Error while trying to acquire lock:", err)
			return false
		}
		if result {
			return true // 获取锁成功
		}

		// 如果没有立即获取到锁，则等待一段时间后重试
		if time.Now().After(endTime) {
			return false // 等待超时，获取锁失败
		}
		time.Sleep(100 * time.Millisecond) // 等待时间间隔后重试
	}
}

// Unlock 释放锁
func Unlock(redis *redis.Client, key string) {
	_, err := redis.Del(context.Background(), key).Result()
	if err != nil {
		helper.InfoLog("Error while trying to release lock:", err)
	}
}
